import 'package:flutter/material.dart';
import 'level_models.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LevelManager with ChangeNotifier {
  final List<LevelCategory> categories = [
    const LevelCategory(name: '加法', icon: Icons.add),
    const LevelCategory(name: '减法', icon: Icons.remove),
    const LevelCategory(name: '乘法', icon: Icons.close),
    const LevelCategory(name: '除法', icon: Icons.exposure_zero),
    const LevelCategory(name: '综合', icon: Icons.extension),
  ];

  final List<DifficultyTier> difficultyLevels = [
    const DifficultyTier(
      level: 1,
      name: '初级',
      timeLimit: Duration(minutes: 1),
      numberRange: NumberRange(0, 10),
    ),
    const DifficultyTier(
      level: 2,
      name: '中级',
      timeLimit: Duration(minutes: 1),
      numberRange: NumberRange(0, 50),
    ),
    const DifficultyTier(
      level: 3,
      name: '高级',
      timeLimit: Duration(minutes: 1),
      numberRange: NumberRange(0, 100),
    ),
  ];

  final Map<String, LevelStatus> _statusMap = {};

  Future<LevelStatus> getStatus(String levelId) async {

    // 新增：优先从SharedPreferences读取已完成状态
    final prefs = await SharedPreferences.getInstance();
    final savedStatus = await prefs.getString(levelId);
    if (savedStatus == 'completed') {
      return LevelStatus.completed;
    }
    
    // 检查是否满足解锁条件
    final previousLevelId = _getPreviousLevelId(levelId);
    if (previousLevelId != null) {
      final previousStatus = await getStatus(previousLevelId);
      if (previousStatus == LevelStatus.completed) {
        return LevelStatus.unlocked;
      }
    }
    // 默认第一个关卡解锁（加法1级）
    if (levelId == '加法1') {
      return LevelStatus.unlocked;
    }

    return _statusMap.putIfAbsent(levelId, () => LevelStatus.locked);
  }
  
  String? _getPreviousLevelId(String levelId) {
    // 实现获取前一个关卡的逻辑
    // 这里简化实现，实际应根据具体关卡结构返回正确的前一个关卡ID
    final categories = ['加法', '减法', '乘法', '除法'];
    final difficultyLevels = [1, 2, 3];
    
    final category = levelId.substring(0, levelId.length - 1);
    final difficulty = int.tryParse(levelId.substring(levelId.length - 1));
    
    if (difficulty == null) return null;
    
    if (difficulty > 1) {
      return '${category}${difficulty - 1}';
    } else {
      // 找到前一个分类
      final currentIndex = categories.indexOf(category);
      if (currentIndex > 0) {
        return '${categories[currentIndex - 1]}3';
      }
    }
    return null;
  }

  void completeLevel(String levelId, int score) {
    _statusMap[levelId] = LevelStatus.completed;
    notifyListeners();
  }

  bool canUnlockNextLevel(String currentLevelId) {
    final status = getStatus(currentLevelId);
    if (status == LevelStatus.completed) {
      return true;
    }
    return false;
  }
}